import React, { useState } from 'react'
import NavBar from '@/components/NavBar'
import styles from './index.module.scss'
import Input from '@/components/Input'
import classNames from 'classnames'
import { useFormik } from 'formik'
import * as Yup from 'yup'
import { useDispatch } from 'react-redux'
import { login, senCode } from '@/store/actions/login'
import { Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'
export default function Login() {
  const history = useHistory()
  const location = useLocation<{ from: string }>()
  // const location = useLocation()
  // console.log(location);

  // 控制倒计时
  const [time, setTime] = useState(0)
  const dispatch = useDispatch()

  const onExtraClick = async () => {
    if (time > 0) return
    if (!/^1[3-9]\d{9}$/.test(mobile)) {
      formik.setTouched({
        mobile: true,
      })
      return
    }
    try {
      await dispatch(senCode(mobile) as any)
      Toast.show({
        content: '获取验证码成功',
        duration: 1000,
        icon: 'success',
      })
      setTime(60)
      // 需要获取最新的时间 需要写成箭头函数的形式，因为形参是最新的值
      let timer = window.setInterval(() => {
        setTime((time) => {
          if (time === 1) {
            clearInterval(timer)
          }
          return time - 1
        })
      }, 1000)
    } catch (error: any) {
      Toast.show({
        content: error.response.data.message,
        duration: 1000,
      })
    }
  }
  // 使用formik
  const formik = useFormik({
    // 初始值
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    onSubmit: (values) => {
      // console.log(values);
      dispatch(login(values) as any)
      Toast.show({
        content: '登录成功',
        icon: 'success',
      })
      const pathname = location.state ? location.state.from : '/home'
      history.replace(pathname)
    },
    // 使用Yup进行表单校验
    validationSchema: Yup.object({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号错误'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码错误'),
    }),
  })
  // console.log(formik);
  const {
    values: { mobile, code },
    handleChange,
    handleSubmit,
    handleBlur,
    touched,
    errors,
    isValid,
  } = formik
  return (
    <div className={styles.root}>
      {/* 导航栏组件 */}
      <NavBar>登录</NavBar>
      <div className="content">
        <h3>短信登录</h3>
        {/* form表单组件 */}
        <form onSubmit={handleSubmit}>
          <div className="input-item">
            <Input placeholder="请输入手机号" value={mobile} onChange={handleChange} name="mobile" autoComplete="off" onBlur={handleBlur} maxLength={11} />

            {touched.mobile && errors.mobile ? <div className="validate">{errors.mobile}</div> : null}
          </div>
          <div className="input-item">
            <Input autoComplete="off" placeholder="请输入验证码" extra={time === 0 ? '获取验证码' : time + 's后获取'} onExtraClick={onExtraClick} value={code} onChange={handleChange} name="code" onBlur={handleBlur} maxLength={6} />
            {touched.code && errors.code ? <div className="validate">{errors.code}</div> : null}
          </div>
          {/* 登录按钮 */}
          <button type="submit" className={classNames('login-btn', isValid ? '' : 'disabled')} disabled={!isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  )
}
